package de.htwg_konstanz.infen.aufg3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;

public enum DefineOccurenceHelper {

	INSTANCE;

	private HashMap<String, CustomHashMapValueItem> dataGuide;

	public HashMap<String, CustomHashMapValueItem> defineOccurence(
			File _xmlFile, HashMap<String, CustomHashMapValueItem> _dataGuide)
			throws FileNotFoundException, DocumentException {

		this.dataGuide = _dataGuide;

		Document xmlFile = Dom4JDocHelper.getDocFromXML(_xmlFile);
		treeWalk(xmlFile);

		return this.dataGuide;
	}

	public HashMap<String, CustomHashMapValueItem> defineOccurence(
			String _xmlPath, HashMap<String, CustomHashMapValueItem> _dataGuide)
			throws FileNotFoundException, DocumentException {

		return this.defineOccurence((new File(_xmlPath)), _dataGuide);
	}

	private void treeWalk(Document _doc) {
		Element root = _doc.getRootElement();
		dataGuide.get(Dom4JDocHelper.transform2CustomPath(root.getPath()))
				.increment();
		List<Element> alist = ((Element) root).elements();

		if (!alist.isEmpty())
			for (Element element : alist)
				dataGuide.get(
						Dom4JDocHelper.transform2CustomPath(element.getPath()))
						.increment();

		checkPossibilities(Dom4JDocHelper.transform2CustomPath(root.getPath()));
		treeWalk(root);
	}

	private void treeWalk(Element _element) {
		for (int i = 0, size = _element.nodeCount(); i < size; i++) {
			Node node = _element.node(i);
			if (node instanceof Element) {
				List<Element> alist = ((Element) node).elements();
				if (!alist.isEmpty()) {
					for (Element value : alist) {
						dataGuide.get(
								Dom4JDocHelper.transform2CustomPath(value
										.getPath())).increment();
					}
					checkPossibilities(Dom4JDocHelper.transform2CustomPath(node
							.getPath()));
				}
				treeWalk((Element) node);
			}
		}
	}

	private void checkPossibilities(String _key) {
		TreeSet<String> possibleList = DataGuideHelper.getAllChilds(_key,
				dataGuide);

		if (!possibleList.isEmpty() && possibleList != null) {
			for (String value : possibleList) {
				CustomHashMapValueItem child = dataGuide.get(_key
						+ DataGuideHelper.itemSeperator + value);
				int counter = child.getCOUNTER();

				if (counter == 0)
					child.setMIN(counter);
				else
					child.setMAX(counter);

				child.resetCounter();
			}
		}
	}
}
